import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../resource/language/generated/l10n.dart';
import '../../dialog/dialog_data.dart';
import '../../dialog/jr_dialog.dart';
import '../../root_page.dart';
import '../screen_utils.dart';

class PermissionUtil {
  ///仅检查权限不请求
  static Future<PermissionStatus> checkPermissions(
      BuildContext context, Permission permission) async {
    return await permission.status;
  }

  // 只应用启动主动取一次位置权限
  static const String hasRequestLocationPermissionKey =
      'has_request_location_permission';
  static get hasRequestLocationPermission => false;

  /// 检查并获取权限
  /// 获取权限规则：
  /// 用户未开关过对应权限时，直接弹系统获取权限dialog；
  /// 权限被用户关时，app引导开启dialog，确定后跳转app权限设置页；
  static Future<PermissionStatus> checkAndRequestPermissions(
      BuildContext context, Permission permission) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    AndroidDeviceInfo? deviceData;
    if (Platform.isAndroid) {
      deviceData = await DeviceInfoPlugin().androidInfo;
    }

    if (permission == Permission.location ||
        permission == Permission.locationWhenInUse) {
      sharedPreferences.setString(hasRequestLocationPermissionKey, '1');
    }

    if (Platform.isAndroid && deviceData!.version.sdkInt < 23) {
      // Android 6.0以下不需要授权
      [permission].request();
      return PermissionStatus.granted;
    }

    if (Platform.isAndroid &&
        deviceData!.version.sdkInt < 31 &&
        (permission == Permission.bluetooth ||
            permission == Permission.bluetoothScan ||
            permission == Permission.bluetoothConnect ||
            permission == Permission.bluetoothAdvertise)) {
      /// Android 12及以上才需要动态申请蓝牙权限
      return PermissionStatus.granted;
    }

    PermissionStatus status = await permission.status;
    if (status == PermissionStatus.granted ||
        status == PermissionStatus.limited) {
      PermissionOverlay.dispose();
      return status;
    }
    String typeName = permission.toString();
    List<String> list = typeName.split('.');
    if (list != null && list.isNotEmpty) {
      typeName = list.last;
    }
    // 第一次直接弹系统获取权限dialog
    if (sharedPreferences.getBool('has_request_$permission') != true) {
      sharedPreferences.setBool('has_request_$permission', true);

      PermissionOverlay.show(permission);
      Map<Permission, PermissionStatus> map = await [permission].request();
      PermissionOverlay.dispose();

      if (map[permission] == PermissionStatus.granted) {
        return PermissionStatus.granted;
      }
    } else {
      // 弹APP的引导dialog，跳转APP权限设置页
      String dialogTitle;
      String dialogContent;
      if (permission == Permission.phone) {
        // 仅Android，电话权限，用户拒绝过，不再主动提示
        return PermissionStatus.denied;
      } else if (permission == Permission.camera) {
        // Android/IOS,相机权限
        dialogTitle = T.current.camera_permission;
        dialogContent = T.current.camera_permission_reason;
      } else if (permission == Permission.location ||
          permission == Permission.locationWhenInUse) {
        // Android/IOS,位置权限
        dialogTitle = T.current.permission_request;
        dialogContent = T.current.permission_request_reason;
      } else if (permission == Permission.storage) {
        // 仅Android，存储权限
        dialogTitle = T.current.storage_permission;
        dialogContent = T.current.storage_permission_reason;
      } else if (permission == Permission.microphone) {
        // Android/IOS,麦克风权限
        dialogTitle = T.current.mic_permission;
        dialogContent = T.current.mic_permission_reason;
      } else if (permission == Permission.photos) {
        // 仅IOS，相册权限
        dialogTitle = T.current.album_permission;
        dialogContent = T.current.album_permission_reason;
      } else if (permission == Permission.contacts) {
        dialogTitle = T.current.permission_request;
        dialogContent = T.current.permission_request_reason;
      } else if (permission == Permission.bluetooth ||
          permission == Permission.bluetoothScan ||
          permission == Permission.bluetoothConnect ||
          permission == Permission.bluetoothAdvertise) {
        /// 仅Android12以上，蓝牙
        dialogTitle = T.current.permission_request;
        dialogContent = T.current.permission_request_reason;
      } else {
        dialogTitle = T.current.permission_request;
        dialogContent = T.current.permission_request_reason;
      }

      PermissionStatus status = PermissionStatus.denied;
      JRDialog.showCommonDialog(
          context: context,
          data: TextWithHorizontalBtnDialogData(
              title: dialogTitle,
              desc: dialogContent,
              onRightBtnPress: () async {
                bool shouldShowRationale =
                    await permission.shouldShowRequestRationale;
                print('shouldShowRationale: $shouldShowRationale');
                if (Platform.isAndroid && shouldShowRationale == true) {
                  // 用户拒绝过，但是并未选中【禁止后不再询问】
                  PermissionOverlay.show(permission);
                  Map<Permission, PermissionStatus> map =
                      await [permission].request();
                  PermissionOverlay.dispose();
                  if (map[permission] == PermissionStatus.granted) {
                    status = PermissionStatus.granted;
                  }
                } else {
                  // 用户拒绝过，但是并选中【禁止后不再询问】,打开权限设置页
                  openAppSettings();
                }
                return true;
              }));
      return status;
    }

    return PermissionStatus.denied;
  }

  ///相册android13以下请求storage  其他版本和ios请求photos
  static Future<PermissionStatus> checkAndRequestPhotosPermissions(
      BuildContext context) async {
    AndroidDeviceInfo? androidInfo;
    if (Platform.isAndroid) {
      androidInfo = await DeviceInfoPlugin().androidInfo;
      if (androidInfo.version.sdkInt < 33) {
        return await PermissionUtil.checkAndRequestPermissions(
            context, Permission.storage);
      }
    }
    return await PermissionUtil.checkAndRequestPermissions(
        context, Permission.photos);
  }

  static Future<bool> checkAndRequestPermissionsResult(
      Permission permission) async {
    PermissionStatus status;
    if (permission == Permission.photos) {
      status = await PermissionUtil.checkAndRequestPhotosPermissions(
          rootNavigatorState.currentContext!);
    } else {
      status = await PermissionUtil.checkAndRequestPermissions(
          rootNavigatorState.currentContext!, permission);
    }
    if (status == PermissionStatus.granted ||
        status == PermissionStatus.limited) {
      return true;
    }
    return false;
  }
}

class PermissionOverlay extends StatelessWidget {
  static OverlayEntry? _overlayEntry;

  static show(Permission permission) async {
    if (_overlayEntry != null) {
      dispose();
    }

    var overlayState = Overlay.of(rootNavigatorState.currentContext!);
    if (overlayState == null) {
      return;
    }

    String? title;
    String? subtitle;
    if (permission == Permission.phone) {
      // 电话权限
      title = T.current.permission_request;
      subtitle = T.current.permission_request_reason;
    } else if (permission == Permission.camera) {
      // Android/IOS,相机权限
      title = T.current.camera_permission;
      subtitle = T.current.camera_permission_reason;
    } else if (permission == Permission.location ||
        permission == Permission.locationWhenInUse) {
      // Android/IOS,位置权限
      title = T.current.permission_request;
      subtitle = T.current.permission_request_reason;
    } else if (permission == Permission.storage) {
      // 仅Android，存储权限
      title = T.current.storage_permission;
      subtitle = T.current.storage_permission_reason;
    } else if (permission == Permission.microphone) {
      // Android/IOS,麦克风权限
      title = T.current.mic_permission;
      subtitle = T.current.mic_permission_reason;
    } else if (permission == Permission.photos) {
      // 仅IOS，相册权限
      title = T.current.album_permission;
      subtitle = T.current.album_permission_reason;
    } else if (permission == Permission.contacts) {
      title = T.current.permission_request;
      subtitle = T.current.permission_request_reason;
    } else if (permission == Permission.bluetooth ||
        permission == Permission.bluetoothScan ||
        permission == Permission.bluetoothConnect ||
        permission == Permission.bluetoothAdvertise) {
      /// 仅Android12以上，蓝牙
      title = T.current.permission_request;
      subtitle = T.current.permission_request_reason;
    }

    if (title == null || title.isEmpty) {
      return;
    }

    _overlayEntry = OverlayEntry(builder: (context) {
      return PermissionOverlay(
        permission: permission,
        title: title ?? "",
        subtitle: subtitle ?? "",
      );
    });

    overlayState.insert(_overlayEntry!);
  }

  static void dispose() {
    if (_overlayEntry != null) {
      _overlayEntry?.remove();
      _overlayEntry = null;
    }
  }

  final Permission? permission;
  final String? title;
  final String? subtitle;
  PermissionOverlay({this.permission, this.title, this.subtitle});

  @override
  Widget build(BuildContext context) {
    return Positioned(
      top: 10 + MediaQuery.of(context).padding.top,
      child: Container(
        width: ScreenUtils.screenW(context) - 20,
        margin: const EdgeInsetsDirectional.only(start: 10, end: 10),
        padding: const EdgeInsetsDirectional.only(
            top: 8, bottom: 8, start: 8, end: 8),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadiusDirectional.circular(16),
          boxShadow: [
            BoxShadow(
                color: Colors.black.withOpacity(0.12),
                offset: const Offset(0, 2),
                blurRadius: 12)
          ],
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              T.current.permission_request,
              style: const TextStyle(
                fontSize: 15,
                fontWeight: FontWeight.w600,
                color: Color(0xff333333),
              ),
            ),
            const SizedBox(
              height: 4,
            ),
            Text(
              "$title",
              style: const TextStyle(
                fontSize: 14,
                color: Color(0xff333333),
              ),
            ),
            const SizedBox(
              height: 4,
            ),
            Text(
              "$subtitle",
              style: const TextStyle(
                fontSize: 14,
                color: Color(0xff333333),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
